package org.xmx0632.test.jmeter.longtcp.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketClient {
	private Socket socket;
	private Aes aes;
	private String gatewayId;

	private BufferedReader br = null;
	private PrintWriter pw = null;

	public SocketClient() {
	}

	public SocketClient(String host, int port, String accessKey, String gatewayId)
			throws UnknownHostException, IOException {
		this.aes = new Aes(accessKey);
		this.gatewayId = gatewayId;
		this.socket = new Socket(host, port);// 172.16.165.11:2002

		br = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
		pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream())));
	}

	public String sendMsg(String msg) throws IOException {
		String request = aes.getEncryptMessageWithAES(msg, gatewayId);
		pw.write(request);
		pw.flush();
		String ret = br.readLine();
		// System.out.println("ret:" + ret);
		return aes.getDecryptMessageWithAES(ret);
	}

	public void closeSocket() {
		if (br != null) {
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (pw != null) {
			try {
				pw.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if ((this.socket != null) && (!this.socket.isClosed())) {
			try {
				this.socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
